package com.nulldev.util.uri.server.v2;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

import com.nulldev.util.io.FileUtil;
import com.nulldev.util.java.DataSet;
import com.nulldev.util.uri.server.HttpPage;
import com.nulldev.util.uri.server.RequestType;

public abstract class HttpPage2 {
	
	private String id;
	
	public HttpPage2(String id) {
		if (!id.startsWith("/"))  {
			id = "/" + id;
		}
		this.id = id.replaceAll(" ", "%20");
	}
	
	public byte[] toBytes(final String str) {
		return str.getBytes();
	}
	
	public String getID() {
		return this.id;
	}

	private String mime = null;
	
	/**
	 * Gets a response.
	 * @returns DataSet[ResponseCode,byte[] data]
	 */
	public abstract DataSet<Integer, InputStream> request(final RequestType type, final String url, final HashMap<String, String> headers,
			final byte[] extraData, final String ip);
	
	public String getMimeType() {
		return this.mime;
	}
	
	public void setMimeType(final String mime) {
		this.mime = mime;
	}
	
	public static HttpPage2 convert(final HttpPage page) {
		final HttpPage2 htp = new HttpPage2(page.getID()) {
			
			@Override
			public DataSet<Integer, InputStream> request(RequestType type, String url, HashMap<String, String> headers,
					byte[] extraData, final String ip) {
				if (page.isOverBytes()) {
					return new DataSet<Integer, InputStream>(200, 
							new ByteArrayInputStream(page.handleRequest_Alt(url, ip, type)));
				}else if (page.sendRaw()) {
					try {
						return new DataSet<Integer, InputStream>(200, 
								new FileInputStream(page.getPath()));
					}catch (Exception e) {
						e.printStackTrace();
					}
				}
				return new DataSet<Integer, InputStream>(200, 
						new ByteArrayInputStream(toBytes(page.handleRequest(url, ip, type))));
			}
		};
		if (page.isCustomMime()) {
			htp.setMimeType(page.getMime());
		}
		return htp;
	}
	
	public InputStream blankStream() {
		return new ByteArrayInputStream(new byte[0]);
	}
	
	public InputStream createStream(final String text) {
		return new ByteArrayInputStream(text.getBytes());
	}
	
	public InputStream createStream(final byte[] data) {
		return new ByteArrayInputStream(data);
	}
}
